﻿using DataAccess;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyPetHub.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Linq;

namespace MyPetHub.Controllers
{
    public partial class HomeController
    {
        public async Task<IActionResult> PetKnowledge()
        {
            await GetBannerAdvertInfo();
            await GetBlockAdvertInfo();

            //获取最多阅读知识
            var mostReadKnowledges = await dbContext.PetKnowledge.OrderByDescending(x => x.readcount).Take(10).ToListAsync();
            var forJsonData = mostReadKnowledges.Select(x => new
            {
                src = "/file/super/imgs/" + x.coverimgsrc,
                navurl = "/Home/PetKnowledgeContent?id=" + x.id,
                title = x.title,
                subTitle = x.subtitle
            }).ToList();

            var carousel = forJsonData.Take(3).ToList();
            ViewData["mostReadKnowledgeCarousel"] = JsonConvert.SerializeObject(carousel, formatSettings);

            var listKnowledge = forJsonData.Skip(3).Take(7).ToList();
            ViewData["mostReadKnowledges"] = JsonConvert.SerializeObject(listKnowledge, formatSettings);

            //知识集中排除的故事
            List<long> eliminatedIDs = new List<long>();
            eliminatedIDs.AddRange(mostReadKnowledges.Select(x => x.id).ToList());
            ViewData["eliminatedIDs"] = JsonConvert.SerializeObject(eliminatedIDs, formatSettings);

            //部分页每批次获取数据量
            ViewData["perBatchCount"] = perBatchCount;

            return View();
        }

        //宠物知识批次获取
        [HttpPost]
        public async Task<IActionResult> PetKnowledge_Partial([FromBody] object json)
        {
            JObject jobj = JObject.Parse(json.ToString());
            string searchContent = jobj["searchContent"].ToString();
            long lastPetStoryID = long.Parse(jobj["lastPetStoryID"].ToString());
            List<long> eliminatedIDs = JsonConvert.DeserializeObject<List<long>>(jobj["eliminatedIDs"].ToString()) ?? new List<long>();
            int knowledgeType = int.Parse(jobj["knowledgeType"].ToString());

            List<PetKnowledge> pkList = null;
            if (string.IsNullOrEmpty(searchContent))
            {
                if (knowledgeType == 0)
                    pkList = await dbContext.PetKnowledge.OrderBy(x => x.id).Where(x => x.id > lastPetStoryID).Take(perBatchCount + 10).ToListAsync();
                else
                    pkList = await dbContext.PetKnowledge.OrderBy(x => x.id).Where(x => x.id > lastPetStoryID && x.speciesid == knowledgeType).Take(perBatchCount + 10).ToListAsync();
            }
            else
            {
                if(knowledgeType == 0)
                    pkList = dbContext.PetKnowledge.FromSqlRaw($"select * from petknowledge where match(content) against('{searchContent}')").OrderBy(x => x.id).
                                Where(x => x.id > lastPetStoryID).Take(perBatchCount + 10).ToList();
                else
                    pkList = dbContext.PetKnowledge.FromSqlRaw($"select * from petknowledge where match(content) against('{searchContent}')").OrderBy(x => x.id).
                                Where(x => x.id > lastPetStoryID && x.speciesid == knowledgeType).Take(perBatchCount + 10).ToList();
            }

            pkList = pkList.Where(x => !eliminatedIDs.Where(s => s == x.id).Any()).Take(perBatchCount).ToList();//排除top10

            List<PetKnowledgeModel> rpkmList = new List<PetKnowledgeModel>();
            foreach (PetKnowledge item in pkList)
            {
                PetKnowledgeModel obj = new PetKnowledgeModel();
                obj.id = item.id;
                obj.imgurl = item.coverimgsrc;
                obj.title = item.title;
                obj.subtitle = item.subtitle;
                obj.species = speciesinfoDict[item.speciesid ?? 1];
                rpkmList.Add(obj);
            }

            return View(rpkmList);
        }

        //养宠知识内容
        [HttpGet]
        public async Task<IActionResult> PetKnowledgeContent()
        {
            long id = long.Parse(Request.Query["id"].ToString());
            var petKnowledge = await dbContext.PetKnowledge.Where(x => x.id == id).FirstOrDefaultAsync();
            if (petKnowledge == null)
            {
                throw new Exception("数据不存在" + id);
            }

            await GetBlockAdvertInfo();
            await LogPetKnowledgeAccessCount(id);

            var petKnowledges = await dbContext.PetKnowledge.FromSqlRaw($"select * from petstory where match(content) against('{petKnowledge.title}')").OrderBy(x => x.id).Take(5).ToListAsync();
            petKnowledges = petKnowledges.Where(x => x.id != petKnowledge.id).Take(4).ToList();//排除当前故事
            ViewData["SimilarKnowledges"] = petKnowledges;
            return View(petKnowledge);
        }

        //记录养宠知识访问次数
        public async Task LogPetKnowledgeAccessCount(long dataID)
        {
            ReadCountHeap? rchObj = await dbContext.ReadCountHeap.Where(x => x.merchantid == -1 && x.id == dataID).FirstOrDefaultAsync();
            if (rchObj != null)
            {
                rchObj.readcount += 1;
                if (rchObj.readcount >= accessCountHeap)
                {
                    var statObj = await dbContext.StatisticsInfo.Where(x => x.id == 3).FirstOrDefaultAsync();
                    statObj.readcount += rchObj.readcount;

                    var pkObj = await dbContext.PetKnowledge.Where(x => x.id == dataID).FirstOrDefaultAsync();
                    pkObj.readcount += rchObj.readcount;

                    rchObj.readcount = 0;
                }
            }
            else
            {
                ReadCountHeap newRchObj = new ReadCountHeap();
                newRchObj.merchantid = -1;
                newRchObj.id = dataID;
                newRchObj.readcount = 1;
                await dbContext.ReadCountHeap.AddAsync(newRchObj);
            }

            await dbContext.SaveChangesAsync();
        }
    }
}
